package com.utils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;

public class FileDownloadUtils {

    /**
     * 网络url下载
     */
    public static void downloadFileURL(String minioUrl, HttpServletRequest request, HttpServletResponse response) {
        try {
            URL url = new URL(minioUrl);
            URLConnection conn = url.openConnection();
            InputStream inStream = conn.getInputStream();
            //对文件名进行编码防止中文乱码
            String filename = FileDownloadUtils.encodeDownloadFilename("文件.pdf", request);
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition", "attachment; filename=" + filename);

            OutputStream out = response.getOutputStream();

            byte[] buffer = new byte[8192];
            int length;
            while ((length = inStream.read(buffer)) != -1) {
                out.write(buffer, 0, length);
            }
            inStream.close();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 下载文件时，针对不同浏览器，进行附件名的编码
     *
     * @param filename 载文件名
     * @param request 请求request
     * @return 编码后的下载附件名
     * @throws IOException
     */
    public static String encodeDownloadFilename(String filename, HttpServletRequest request)
            throws IOException {
        String agent = request.getHeader("user-agent");//获得游览器
        if (agent.contains("Firefox")) { // 火狐浏览器
            filename = "=?UTF-8?B?"
                    + Arrays.toString(Base64.getEncoder().encode(filename.getBytes(StandardCharsets.UTF_8)))
                    + "?=";
            filename = filename.replaceAll("\r\n", "");
        } else { // IE及其他浏览器
            filename = URLEncoder.encode(filename, "utf-8");
            filename = filename.replace("+"," ");
        }
        return filename;
    }
}
